package org.sauceggplant;

import java.io.*;

/**
 * 文件实用类
 *
 * @author jacob
 * @version 0.1
 */
public class FileUtil {

    public static final int BLOCK_SIZE = 4096;

    public static byte[] file2bytes(File file) {
        byte[] data = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[BLOCK_SIZE];
            int length = 0;
            while ((length = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
            fis.close();
            bos.close();
            data = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    public static File bytes2file(byte[] bytes, String fileName) {
        InputStream in = new ByteArrayInputStream(bytes);
        File file = new File(fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            int length = 0;
            byte[] buffer = new byte[BLOCK_SIZE];
            while ((length = in.read(buffer)) != -1) {
                fos.write(buffer, 0, length);
            }
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }

    public static File byteArray2file(byte[][] bytes, String fileName) {
        File file = new File(fileName);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            for (int i = 0; i < bytes.length; i++) {
                InputStream in = new ByteArrayInputStream(bytes[i]);
                int length = 0;
                byte[] buffer = new byte[BLOCK_SIZE];
                while ((length = in.read(buffer)) != -1) {
                    fos.write(buffer, 0, length);
                }
            }
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fos) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
}
